#encoding=utf8
'''
Created on Nov 25, 2014

@author: jingyang <jingyang@smalltreemedia.com>
'''
from django import forms
from django.utils import timezone

from suit.widgets import EnclosedInput, SuitDateWidget

from core.widgets import CustomCheckboxSelectMultiple, CustomAdminImageWidget
from sub_info.models import UPDATE_PURPOSE, SubInfo, PREFIX, UPDATE_ASSETS,\
    UPDATE_META, RESUB_REQ, RejImg
from app_info.models import AppVersion
from utils import rename_file
from django.forms.widgets import DateInput


class SubInfoForm(forms.ModelForm):

    error_messages = {'required': 'This field is required.',
        'request_exists': 'Submission Request for selected version of the app exists.',
        'version_invalid': 'Version selected for the app invalid.',
        'extra_info_missing': "Please complete the Extra section in App Info page first.",
        'edqa_invalid': 'Can not be the day before today.'}

#    update_for = forms.MultipleChoiceField(required=False, label=u'Update Purpose',
#        widget=CustomCheckboxSelectMultiple, choices=UPDATE_PURPOSE)
    update_assets = forms.MultipleChoiceField(required=False, label=u'Update on Graphics Assets',
        widget=CustomCheckboxSelectMultiple, choices=UPDATE_ASSETS)
    update_meta = forms.MultipleChoiceField(required=False, label=u'Update on Meta Data',
        widget=CustomCheckboxSelectMultiple, choices=UPDATE_META)
    prefix = forms.CharField(required=False, label=u'Territories',
        max_length=1, widget=forms.Select(choices=PREFIX,
            attrs={'style': 'width: 130px;'}))
    rating = forms.CharField(required=False, label='Suggestion on App Rating',
            max_length=500)
    resub_req = forms.MultipleChoiceField(required=False, label=u'Requests',
        widget=CustomCheckboxSelectMultiple, choices=RESUB_REQ)
    edsr = forms.DateField(required=False, help_text='YYYY-MM-DD',
                           label='Estimated Date of Submission Ready')

    class Meta:
        model = SubInfo
        widgets = {'etqa': EnclosedInput(append='Day(s)'),
                   'edqa': SuitDateWidget}

    def clean_edqa(self):
        edqa = self.cleaned_data.get('edqa')
        resub_req = self.cleaned_data.get('resub_req')
        if resub_req:
            if 'UBF' in resub_req:
                if not edqa:
                    raise forms.ValidationError(self.error_messages['required'])
        if edqa and edqa < timezone.now().date():
            raise forms.ValidationError(self.error_messages['edqa_invalid'])
        return edqa

    def clean_etqa(self):
        etqa = self.cleaned_data.get('etqa')
        resub_req = self.cleaned_data.get('resub_req')
        if resub_req:
            if 'UBF' in resub_req:
                if not etqa:
                    raise forms.ValidationError(self.error_messages['required'])
        return etqa

    def clean_app(self):
        app = self.cleaned_data.get('app')
        if app:
            if not hasattr(app, 'appextrainfo'):
                raise forms.ValidationError(self.error_messages['extra_info_missing'])
            else:
                extra = app.appextrainfo
                if not extra.media_local or not extra.media_remote or not extra.display_name:
                    raise forms.ValidationError(self.error_messages['extra_info_missing'])
        return app

    def clean_resub_req(self):
        resub_req = self.cleaned_data.get('resub_req')
        if not resub_req:
            resub_req = ""
        return resub_req

    def clean_valid_date(self):
        valid_date = self.cleaned_data.get('valid_date')
        if not valid_date:
            if self.cleaned_data.get('validation') == 'V':
                valid_date = timezone.localtime(timezone.now()).date()
        return valid_date

#    def clean_binary_ready_date(self):
#        binary_ready_date = self.cleaned_data.get('binary_ready_date')
#        if not binary_ready_date:
#            if self.cleaned_data.get('binary_status') == 'Y':
#                binary_ready_date = timezone.localtime(timezone.now()).date()
#        return binary_ready_date
#
#    def clean_meta_ready_date(self):
#        meta_ready_date = self.cleaned_data.get('meta_ready_date')
#        if not meta_ready_date:
#            if self.cleaned_data.get('meta_status') == 'Y':
#                meta_ready_date = timezone.localtime(timezone.now()).date()
#        return meta_ready_date
#
#    def clean_binary_uploaded_date(self):
#        binary_uploaded_date = self.cleaned_data.get('binary_uploaded_date')
#        if not binary_uploaded_date:
#            if self.cleaned_data.get('binary_upload_status') == 'Y':
#                binary_uploaded_date = timezone.localtime(timezone.now()).date()
#        return binary_uploaded_date
#
#    def clean_app_submit_date(self):
#        print 'test'
#        app_submit_date = self.cleaned_data.get('app_submit_date')
#        if not app_submit_date:
#            if self.cleaned_data.get('status') == 'S':
#                app_submit_date = timezone.localtime(timezone.now()).date()
#        return app_submit_date

    def clean_sub_person(self):
        sub_person = self.cleaned_data.get('sub_person')
        if not sub_person:
            if self.cleaned_data.get('status') == 'S':
                sub_person = 'Richard.Du'
        return sub_person

    def clean_validation(self):
        validation = self.cleaned_data.get('validation')
        if not validation:
            if self.instance.validation:
                validation = self.instance.validation
                self.changed_data.remove('validation')
            else:
                validation = 'P'
        return validation

    def clean_binary_status(self):
        binary_status = self.cleaned_data.get('binary_status')
        if not binary_status:
            binary_status = 'N'
        return binary_status

    def clean_meta_status(self):
        meta_status = self.cleaned_data.get('meta_status')
        if not meta_status:
            meta_status = 'N'
        return meta_status

    def clean_binary_upload_status(self):
        binary_upload_status = self.cleaned_data.get('binary_upload_status')
        if not binary_upload_status:
            binary_upload_status = 'N'
        return binary_upload_status

    def clean_status(self):
        status = self.cleaned_data.get('status')
        if not status:
            status = ''
        return status

    def clean_version(self):
        version = self.cleaned_data.get('version')
        app = self.cleaned_data.get('app')
        if version and app:
            if not AppVersion.objects.filter(app=app, code=version).exists():
                raise forms.ValidationError(self.error_messages['version_invalid'])
            if self.cleaned_data.get('is_resub', 'N') == 'N':
                if SubInfo.objects.filter(app=app, version=version).exclude(pk=self.instance.pk).exclude(validation='C').exists():
                    raise forms.ValidationError(self.error_messages['request_exists'])
        return version

    def clean_rej(self):
        rej = self.cleaned_data.get('rej')
        if not rej:
            if self.cleaned_data.get('is_resub') == 'Y':
                raise forms.ValidationError(self.error_messages['required'])
        return rej

    def clean_update_assets(self):
        update_assets = self.cleaned_data.get('update_assets')
        if not update_assets:
            return ""
        return update_assets

    def clean_update_meta(self):
        update_meta = self.cleaned_data.get('update_meta')
        if not update_meta:
            return ""
        return update_meta

#    def clean(self):
#        print '--->', self._errors
#        return self.cleaned_data


class RejImgForm(forms.ModelForm):

    class Meta:
        model = RejImg
        widgets = {'img': CustomAdminImageWidget}

    def clean_img(self):
        img = self.cleaned_data.get('img')
        if img and 'img' in self.changed_data:
            return rename_file(img)
        return img
